function [worksheetName2Save] = ImportData_Function(SpreadsheetName,TabName,DesiredDataName,subfolder,AcceptableTotalRange)
%Step1_Optimize_ReverseFracCryst_Iceland Big function version?


%profile on
addpath('Z_FractionalCrystallizationScripts')
addpath('Z_NeededScripts')
addpath('Z_NeededDatasets')


addpath(subfolder)
worksheetName2Save=sprintf('%s_%s_%s',SpreadsheetName,TabName{1},DesiredDataName);


%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%% Step 1: import the data from the spreadsheet, simultaneously normalize and calculate new parameters (such as Mg#).
load('PUM') % Loads trace element source, if you want to change it, change it here!
TraceElements4Normalization_PUM = Sources_Trace;

Labels2Plot = [];

targetStrings_Majors = {'T(C)', 'P(kbars)','SiO2','TiO2','Al2O3', 'Cr2O3','FeO','MnO','MgO','CaO','Na2O','K2O','P2O5','NiO','H2O'};

ElementRatios= {'Th' 'U'; 'Lu' 'Hf'; 'Sm' 'Nd'; 'Lu' 'Sc'; 'Hf' 'Nd'; 'La' 'Sm'; 'Rb' 'Sr'; 'Eu' 'Sm'; 'Eu' 'Gd'; 'Nd' 'Zr'; 'Sm' 'Yb';...
    'Zr' 'Y'; 'Nb' 'Y'; 'Gd' 'Yb';  'Zr' 'Yb'; 'Zr' 'Hf'; 'Nb' 'Ta'; 'Ba' 'La'; 'Ba' 'Pb'; 'U' 'Pb'; 'Eu' 'Eu'; 'K' 'U'}; 

%targetStrings_Isotopes = {'87Sr/86Sr'	'143Nd/144Nd'	'206Pb/204Pb'	'207Pb/204Pb'	'208Pb/204Pb'	'176Hf/177Hf' '230Th/238U' '226Ra/230Th'};

targetStrings_Isotopes = {'SR87_SR86'	'ND143_ND144'	'PB206_PB204'	'PB207_PB204'	'PB208_PB204'	'HF176_HF177' 'TH230_U238_ACTIVITY' 'TH230_TH232_ACTIVITY' 'U238_TH232_ACTIVITY' 'RA226_TH230_ACTIVITY'};
%second option is for EarthChem label format, first is for Gale label format

[xlsNumbers, xlsText,xlsRAW] = xlsread('Ds_RevPet', 'TraceElementOrder');
[ElementRow,ElementColumn]= find(strcmp(xlsRAW,'Elements')==1);
[LastElementRow,LastElementColumn]= find(strcmp(xlsRAW,'LastElement')==1);
% Matrix with element labels
targetStrings_Trace = xlsRAW(ElementRow+1:LastElementRow-1, ElementColumn)';
%get element info
ElementsInfo = (xlsRAW(ElementRow+1:LastElementRow-1,ElementColumn+1));
i1 = cellfun(@ischar,ElementsInfo);
sz = cellfun('size',ElementsInfo(~i1),2);
ElementsInfo(i1) = {nan(1,sz(1))};
ElementsInfo = cell2mat(ElementsInfo)';

%gets compositions to normalize by
xlsRAW_strings=cellfun(@num2str,xlsRAW,'un',0);


clear DataRatios
for gg = 1:size(ElementRatios,1)
    for ggg = 1:size(ElementRatios,2)
%         %for major and trace element matricies:
%         ElementRatiosIndex(gg,ggg) =  find(strcmp(targetStrings_Trace_all,ElementRatios(gg,ggg)));
        %for trace element only matricies:
        ElementRatiosIndex(gg,ggg) =  find(strcmp(targetStrings_Trace,ElementRatios(gg,ggg)));
    end
end


for kk = 1:size(ElementRatios,1)
    RatioLabels{kk}=sprintf('%s/%s',ElementRatios{kk,1}, ElementRatios{kk,2});
end

targetElements ={ 'SiO2'	'TiO2' 'Al2O3'	'Cr2O3'  'FeO'	'MnO'	'MgO'	'CaO'    'Na2O'	'K2O' 'P2O5' 'Fe2O3'};
[A,targetStrings_Majors_Tormey_Indicies] = ismember(targetElements, targetStrings_Majors);

Elements = {'T(C)' 'P(kbars)' ...
    'SiO2'	'TiO2'	  'Al2O3' 'Cr2O3'	  'FeO'	  'MnO'	  'MgO'	  'CaO' 'Na2O'   'K2O' 'P2O5' 'NiO' 'H2O' 'total'...
    'Mg#' 'NaK#' 'CaO/Al2O3 wt%' 'CaO/Al2O3 moles' 'Na2O/FeO' 'K2O/TiO2' '1-Mg#' 'Qtz' 'Plag' 'Oliv' 'Cpx' 'Ox' 'Or' 'Ap'};

[A,ElementIndicies4Target_Sum] = ismember(Elements, targetStrings_Majors);

runningTrace=[]; 
runningMajors=[]; 
runningLabels=[]; 
runningTormey=[]; 
runningColors_FILL=[]; 
runningColors_LINE=[]; 
runningLATLONG=[];
runningTabNames=[]; 
runningIsotopes=[];
runningDataRatios=[];
runningMarkers=[];
runningRegions =[]; 
runningSamples =[]; 
runningVariableNames=[]; 
runningDataNames = []; 

runningINFO=[]; 
runningPHASES=[]; 
runningF=[]; 
runningEXPT=[]; 
runningTYPE=[]; 
runningSizes=[]; 
runningMajors_Unnorm=[]; 

for i=1:size(TabName,2)   

    [MajorElements, Major_Labels, Major_Colors_Fill,Major_Colors_Line,Lat,Long,Regions, Markers,Samples,Info,Phases,F,Expt,Type,Sizes] = reorderElements_Rows(SpreadsheetName, TabName{i}, DesiredDataName, targetStrings_Majors,'FirstMajor','LastMajor'); 
            %Make empty cells for optional headings that were not
            %specified
            OptionalHeadings = {'Lat','Long','Samples','Info','Phases','F','Expt','Type'};
            for hgp = 1:size(OptionalHeadings,2)
                if isempty(eval(OptionalHeadings{hgp}))==1
                    
                    padNAN = cell(size(MajorElements,1),1);
                    assignin('base',OptionalHeadings{hgp},padNAN)
                end
            end
    
    
    
    [TraceElements, Trace_Labels] = reorderElements_Rows(SpreadsheetName, TabName{i}, DesiredDataName, targetStrings_Trace,'FirstTraceIsotope','LastTraceIsotope'); 

    %assignin('base', (TabName{i}),sumMgNumNorm(xlsread('master_data',char(TabName(i)))));  
    %assignin('base', (TabName{i}),sumMgNumNorm(MajorElements));   
    assignin('base', (TabName{i}),sumMgNumNorm_PT(MajorElements,targetStrings_Majors,ElementIndicies4Target_Sum,AcceptableTotalRange));   

    assignin('base', [TabName{i},'_Trace'],TraceElements);    
    % if you don't want to normalize use this instead:
     %   assignin('base', (TabName{i}),data);      
    
 
    assignin('base', [TabName{i},'_Colors_FILL'],Major_Colors_Fill);  
    assignin('base', [TabName{i},'_Colors_LINE'],Major_Colors_Line);    
    assignin('base', [TabName{i},'_Labels'],Major_Labels);  
    assignin('base', [TabName{i},'_Lat'],Lat);
    assignin('base', [TabName{i},'_Long'],Long);
    assignin('base', [TabName{i},'_Markers'],Markers);  
    assignin('base', [TabName{i},'_Regions'],Regions); 
    assignin('base', [TabName{i},'_Samples'],Samples); 
    
    %calculates the Tormey components of all the data 
    assignin('base', [TabName{i},'_Tormey'],TormeyProjection(MajorElements,targetStrings_Majors,targetStrings_Majors_Tormey_Indicies));
    
    [Isotopes, Isotope_Labels] = reorderElements_Rows(SpreadsheetName, TabName{i}, DesiredDataName, targetStrings_Isotopes,'FirstTraceIsotope','LastTraceIsotope'); 
    assignin('base', [TabName{i},'_Isotopes'],Isotopes);   


    EuCol = find(strcmp(targetStrings_Trace,'Eu'));
    SmCol = find(strcmp(targetStrings_Trace,'Sm'));
    GdCol = find(strcmp(targetStrings_Trace,'Gd'));

    clear DataRatios
    for gg = 1:size(ElementRatios,1)
        DataRatios(:,gg) = TraceElements(:,ElementRatiosIndex(gg,1)) ./TraceElements(:,ElementRatiosIndex(gg,2)); 
        DataRatios(:,21) = 2.*(TraceElements(:,EuCol)./TraceElements4Normalization_PUM(EuCol))./((TraceElements(:,SmCol)./TraceElements4Normalization_PUM(SmCol))+(TraceElements(:,GdCol)./TraceElements4Normalization_PUM(GdCol))); 
        assignin('base',sprintf('%s_DataRatios',TabName{i}), DataRatios); 
    end

    

    runningMajors_Unnorm = [runningMajors_Unnorm; MajorElements]; 
    runningTrace = [runningTrace; TraceElements];
    runningMajors = [runningMajors; sumMgNumNorm_PT(MajorElements,targetStrings_Majors,ElementIndicies4Target_Sum,AcceptableTotalRange)];
    runningLabels = [runningLabels; Major_Labels];
    
    runningTormey = [runningTormey; TormeyProjection(MajorElements,targetStrings_Majors,targetStrings_Majors_Tormey_Indicies)];
    
    
    runningColors_FILL = [runningColors_FILL; Major_Colors_Fill];
    runningColors_LINE = [runningColors_LINE; Major_Colors_Line];
    runningLATLONG = [runningLATLONG; ([Lat Long])];
    runningIsotopes = [runningIsotopes; Isotopes];
    runningDataRatios = [runningDataRatios; DataRatios];
    runningMarkers = [runningMarkers; Markers];
    runningRegions = [runningRegions; Regions];
    runningSamples = [runningSamples; Samples];
 
    runningINFO = [runningINFO; Info];
    runningPHASES = [runningPHASES; Phases];
    runningF = [runningF; F];
    runningEXPT = [runningEXPT; Expt];
    runningTYPE = [runningTYPE; Type];
    runningSizes = [runningSizes; Sizes];
    
     C    = cell(size(Major_Labels,1),1);
     C(:) = TabName(i);
    
     
     
     D    = cell(size(Major_Labels,1),1);
     D(:) = {DesiredDataName};
 

    runningTabNames=[runningTabNames; C];
    runningDataNames=[runningDataNames;D];
    
    TabVariableNames = sprintf('%s'', ''%s'', ''%s'',''%s'',''%s'',''%s'',''%s'',''%s'',''%s', ...
    sprintf('%s',TabName{i}), sprintf('%s_Isotopes',TabName{i}), sprintf('%s_Trace',TabName{i}),sprintf('%s_DataRatios',TabName{i}),...
    sprintf('%s_Tormey',TabName{i}),sprintf('%s_Colors',TabName{i}),sprintf('%s_Regions',TabName{i}),sprintf('%s_Markers',TabName{i}),sprintf('%s_Labels',TabName{i}),sprintf('%s_Samples',TabName{i}));

    assignin('base', [TabName{i},'_VariableNames'],TabVariableNames); 
    


    runningVariableNames=[runningVariableNames,''',''', TabVariableNames];
    
    runningMajors_Unnorm(:,1:2)=[];
    runningMajors_Unnorm(:,end+1)=nansum(runningMajors_Unnorm(:,1:12),2);



    
end
ElementRatios{21,1}='Eu';
ElementRatios{21,2}='Eu*';



clear DataRatios
    for gg = 1:size(ElementRatios,1)
        DataRatios(:,gg) = TraceElements4Normalization_PUM(:,ElementRatiosIndex(gg,1)) ./TraceElements4Normalization_PUM(:,ElementRatiosIndex(gg,2)); 
        DataRatios(:,21) = 2.*(TraceElements4Normalization_PUM(:,EuCol)./TraceElements4Normalization_PUM(EuCol))./((TraceElements4Normalization_PUM(:,SmCol)./TraceElements4Normalization_PUM(SmCol))+(TraceElements4Normalization_PUM(:,GdCol)./TraceElements4Normalization_PUM(GdCol))); 
    end
DataRatios_TraceElements4Normalization = DataRatios;  
    
    
data = runningMajors;
CombinedLabel = strcat(runningRegions,{'-'}, runningLabels); 
[UniqueLabels,UniqueLabels_Rows] = unique(CombinedLabel,'stable');



% runningLATLONG = str2double(runningLATLONG); 
% runningF = str2double(runningF); 
% 
% if isempty(runningLATLONG)==1
%     runningLATLONG = NaN.*runningMajors(:,1:2); 
% end
% 
% if isempty(runningINFO)==1
%     runningINFO = runningMarkers; 
%     for kk=1:size(runningMarkers,1)
%         runningINFO{kk,1}='NaN'; 
%     end
% end
% 
% if isempty(runningPHASES)==1
%         runningPHASES = runningMarkers; 
%     for kk=1:size(runningMarkers,1)
%         runningPHASES{kk,1}='NaN'; 
%     end
% end
% 
% 
% if isempty(runningF)==1
%     runningF = NaN.*runningMajors(:,1); 
% end
% 
% 
% if isempty(runningEXPT)==1
%         runningEXPT = runningMarkers; 
%     for kk=1:size(runningMarkers,1)
%         runningEXPT{kk,1}='NaN'; 
%     end
% end
% 
% if isempty(runningTYPE)==1
%         runningTYPE = runningMarkers; 
%     for kk=1:size(runningMarkers,1)
%         runningTYPE{kk,1}='NaN'; 
%     end
% end
% 
% if isempty(runningSamples)==1
%         runningSamples = runningMarkers; 
%     for kk=1:size(runningMarkers,1)
%         runningSamples{kk,1}='NaN'; 
%     end
% end




% 'Name of Saved Matlab Workspace:'
% worksheetName2Save

%eval(['save(''',worksheetName2Save,''')'])
%mat2clip(sprintf('dataname = ''%s'';',worksheetName2Save))

eval(['save(''',[pwd '/' subfolder '/' worksheetName2Save '.mat'],''')'])



end

